<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="98px">
      <el-form-item label="渠道" prop="channelId">
        <el-select v-model="queryParams.channelId" placeholder="请选择渠道" @change="changeChannel">
          <el-option v-for="item in channelList" :key="item.id" :label="item.channelName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleImportZhaoShang" v-show="showButton">转换订单</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item label="地址合并选项">
        <el-col :span="18">
          <el-checkbox v-model="channel.extend2.mergedCountry" @change="changeConfig">国家</el-checkbox>
          <el-checkbox v-model="channel.extend2.mergedProvince" @change="changeConfig">州省</el-checkbox>
          <el-checkbox v-model="channel.extend2.mergedUrbanArea" @change="changeConfig">市区</el-checkbox>
          <el-checkbox v-model="channel.extend2.mergedDistrict" @change="changeConfig">区县</el-checkbox>
        </el-col>
        <el-col :span="6">
          <el-input v-model="channel.extend2.delimiter" size="small" width="250px" placeholder="请输入分隔符" @change="changeConfig"clearable></el-input>
        </el-col>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tableDataList" v-show="showHeaderTable" :default-sort = "{prop: 'sort',order:'ascending'}" >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="渠道名称" align="center" prop="channelName" />
      <el-table-column label="网店管家列名称" align="right" prop="wdgjOrderHeader" :show-overflow-tooltip="true" />
      <el-table-column label="渠道列别名" align="left" prop="channelOrderHeader" :show-overflow-tooltip="true" />

      <el-table-column label="是否导入" align="center" prop="enable" class-name="small-padding fixed-width">
      <template slot-scope="scope">
        <!-- <el-switch v-model="scope.row.enable" @change="changeSwitch(scope.row)" active-text="是" inactive-text="否" active-color="#13ce66" inactive-color="#ff4949"></el-switch> -->
        <el-switch v-model="scope.row.enable" @change="changeSwitch(scope.row)" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
      </template>
      </el-table-column>
      <!-- <el-table-column label="排序" align="center" prop="sort" sortable class-name="small-padding fixed-width">
      <template slot-scope="scope">
        <el-button v-show="scope.$index!=0" size="mini" type="text" icon="el-icon-top" @click="handleEditSortTop(scope.$index, scope.row)"></el-button>
        <el-button v-show="tableDataList.length!=0&&scope.$index!=tableDataList.length-1" size="mini" type="text" icon="el-icon-bottom" @click="handleEditSortBottom(scope.$index, scope.row)"></el-button>
      </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteHeader(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改品牌对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="渠道名称">
          {{form.channelName}}
        </el-form-item>
        <el-form-item label="网店管家列名称">
          {{form.wdgjOrderHeader}}
        </el-form-item>
        <el-form-item label="渠道列表名" prop="channelOrderHeader">
          <el-input v-model="form.channelOrderHeader" placeholder="请输入渠道列别名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?channelId=' + this.queryParams.channelId"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :on-error="handleFileError" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
          <!-- <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link> -->
        </div>
        <div class="el-upload__tip" style="color:#ff0000" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" v-loading.fullscreen.lock="loading">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="errorList.title" :visible.sync="errorList.open" width="65%">
      <el-table v-loading="errorList.loading" :data="errorList.datalist">
        <el-table-column label="订单编号" align="center" prop="tradeno" width="130" />
        <el-table-column label="描述" align="center" prop="errmsg" :show-overflow-tooltip="true" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="errorList.open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAccessToken } from '@/utils/auth'
import { getChannelConfig, searchChannel, updateChannelConfig } from '@/api/admin/channel'
import { editOrderHeader, exportWdgjOrder, listOrderHeader,delOrderHeader, wdgjOrderTmplate } from '@/api/admin/order'

export default {
    name: 'OrderImportToWdgj',
    components: {},
    directives: {},
    data() {
      return {
        // 遮罩层
        loading: false,
        showButton: true,
        showHeaderTable: false,
        orderType: '',
        // 订单表头表格数据
        tableDataList: [],
        // 表单参数
        form: {},
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单校验
        rules: {
          channelOrderHeader: [{
            required: true,
            message: "渠道列别名不能为空",
            trigger: "blur"
          }]
        },
        errorList: {
          loading: false,
          title: '异常订单',
          open: false,
          datalist: []
        },
        channelList: [],
        channel: {
          id: undefined, extend2: {
            delimiter: '',
            mergedCountry: false,
            mergedDistrict: false,
            mergedProvince: false,
            mergedUrbanArea: false
          }
        },
        // 查询参数
        queryParams: {
          current: 1,
          size: 10,
          name: undefined,
          key: undefined,
          isSys: undefined
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getAccessToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/admin/order/import"
        }
      }
    },
    created() {
      this._loadChannel();
    },
    methods: {
      _loadChannel() {
        searchChannel({}).then(response => {
          this.channelList = response.data || [];
        });
      },
      changeConfig(val) {
        console.log(this.channel);
        if (this.channel.id === undefined){
          this.msgWarning('请先选择渠道');
          return ;
        }
        let _val={id:this.channel.id,extend2:JSON.stringify(this.channel.extend2)};
        updateChannelConfig(_val).then(response=>{
          console.log(response);
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.current = 1;
        // this.getList();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
      },
      changeChannel(id) {
        console.log(id)
        this.channel.id=id;
        getChannelConfig(id).then(response=>{
          if (response.code === 0) {
            console.log(response.data)
            this.channel.extend2=response.data;
            console.log(this.channel.extend2)
          }
        });
        this._loadOrderHeader(this.channel.id);
      },
      _loadOrderHeader(id) {
        this.loading = true;
        listOrderHeader(id).then(response => {
          this.loading = false;
          if (response.code === 0) {
            this.showHeaderTable = true;
            this.tableDataList = response.data || [];
          } else {
            this.msgError(response.msg);
          }
        });
      },
      /**删除订单表头*/
      handleDeleteHeader(row) {
        delOrderHeader(row.id).then(response=>{
            if (response.code === 0) {
              this.msgSuccess("修改成功");
              this.changeChannel(row.channelId);
            } else {
              this.msgError(response.msg);
            }
        });
      },
      handleEditSortTop (index,row){
        // console.log(index,row)
        if(index===0){
          row.sort=index;
          let _form={id:row.id,sort:row.sort}
          this.update(_form);
        }else{
          let _form={id:row.id,sort:index-1}
          this.update(_form);
          _form={id:this.tableDataList[index-1].id,sort:index}
          this.update(_form);
          row.sort=index-1;
          this.tableDataList[index-1].sort=index;
        }
        this._loadOrderHeader(this.channel.id);
      },
      handleEditSortBottom(index,row){
        if(index===this.tableDataList.length-1){
          row.sort=index;
          let _form={id:row.id,sort:row.sort}
          this.update(_form);
        }else{
          let _form={id:row.id,sort:index+1}
          this.update(_form);
          _form={id:this.tableDataList[index+1].id,sort:index}
          this.update(_form);
          row.sort=index+1;
          this.tableDataList[index+1].sort=index;
        }
      },
      update(_form,showMsg,fn){
        this.loading = true;
        editOrderHeader(_form).then(response => {
          this.loading = false;
          if (response.code === 0) {
            if(showMsg){
              this.msgSuccess("修改成功");
            }
            if(fn){
              fn();
            }
            this._loadOrderHeader(this.channel.id)
          } else {
            this.msgError(response.msg);
          }
        });
      },
      /** 修改按钮操作 */
      handleEdit(row) {
        this.reset();
        const id = row.id || this.ids
        this.form = {
          id: row.id,
          channelId: row.channelId,
          channelName: row.channelName,
          channelOrderHeader: row.channelOrderHeader,
          wdgjOrderHeader: row.wdgjOrderHeader
        };
        this.open = true;
        this.title = '编辑Excel表头列名称';
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            let channelId=this.form.channelId;
            editOrderHeader(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.changeChannel(channelId);
              } else {
                this.msgError(response.msg);
              }
            });
          }
        });
      },
      changeSwitch(row) {
        let _form={id:row.id,enable:row.enable}
        editOrderHeader(_form).then(response => {
          if (response.code === 0) {
            this.msgSuccess("修改成功");
          } else {
            this.msgError(response.msg);
          }
        });
      },
      /** 导入招商按钮操作 */
      handleImportZhaoShang() {
        this.upload.title = "转换订单";
        this.upload.open = true;
        this.orderType = 'zhaoshang';
        console.log(this.queryParams);
        return false;
      },
      /** 下载模板操作 */
      importTemplate() {
        wdgjOrderTmplate().then(response => {
          this.download(response.data);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.showButton = false;
        this.loading = true;
        this.upload.isUploading = true;
        this.upload.open = false;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        console.log(response);

        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        // this.getList();
        if (response.code === 0) {
          let batchNo = response.data || '-1';
          exportWdgjOrder({
            'batchNo': batchNo,
            'channelId':this.queryParams.channelId
          }).then(response => {
            this.download(response.data);
            this.loading = false;
            this.showButton = true;
          });
        } else {
          this.loading = false;
          this.showButton = true;
          this.msgError(response.msg);
        }
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      handleFileError(err, file, fileList) {
        this.showButton = true;
        this.loading = false;
        this.upload.isUploading = false;
        this.msgError(err)
      }
    }
  }
</script>

<style scoped>
  .mixin-components-container {
    background-color: #f0f2f5;
    padding: 30px;
    min-height: calc(100vh - 84px);
  }

  .component-item {
    min-height: 100px;
  }
</style>
